package com.taotao.netty;


import com.taotao.netty.handler.WebSocketHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @className: ImServer
 * @author: ZhangYuQi
 * @date: 2025/2/26 下午3:20
 * @Version: 1.0
 * @description:
 */


public class ImServer {

    public static final Map<String, Channel> USERS=new ConcurrentHashMap<>(1024);

    public static final ChannelGroup GROUP= new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);


    public static void start() throws InterruptedException {

        EventLoopGroup boss= new NioEventLoopGroup();
        EventLoopGroup worker= new NioEventLoopGroup();


        // 绑定端口
        ServerBootstrap bootstrap = new ServerBootstrap();

        bootstrap.group(boss,worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {

                        ChannelPipeline pipeline = socketChannel.pipeline();

                        //添加Http编码解码器
                        pipeline.addLast(new HttpServerCodec())
                                //支持大数据流处理
                                .addLast(new ChunkedWriteHandler())
                                //对Http消息做聚合操作 FullRequest、FullResponse
                                .addLast(new HttpObjectAggregator(1024 * 64))
                                //websocket
                                .addLast(new WebSocketServerProtocolHandler("/"))

                                .addLast(new WebSocketHandler());
                    }
                });

        ChannelFuture future=bootstrap.bind(8969).sync();




    }


}
